package com.skivingcloud.admin.sys.service.impl;

import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.captcha.generator.MathGenerator;
import cn.hutool.core.math.Calculator;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.skivingcloud.admin.sys.entity.SysCaptcha;
import com.skivingcloud.admin.sys.mapper.SysCaptchaMapper;
import com.skivingcloud.admin.sys.service.SysCaptchaService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 *  服务层实现。
 *
 * @author skivingcloud
 * @since 2023-08-28
 */
@Service
public class SysCaptchaServiceImpl extends ServiceImpl<SysCaptchaMapper, SysCaptcha> implements SysCaptchaService {
    
    public static final String CAPTCHA_REDIS_KEY_PREFIX = "sysCaptcha:";
    
    @Resource
    RedisTemplate<String, SysCaptcha> redisTemplate;
    /**
     * 获取图片验证码
     *
     * @param uuid uuid
     */
    @Override
    public BufferedImage getCaptcha(String uuid) throws Exception{
        if(StringUtils.isBlank(uuid)){
            throw new Exception("uuid不能为空");
        }
        ShearCaptcha captchaShear = new ShearCaptcha(200, 60, 6, 2);
        captchaShear.setGenerator(new MathGenerator(1));
//        captchaShear.setBackground(new Color(78, 80, 82, 3));
        captchaShear.createCode();
        int calculateResult = (int) Calculator.conversion(captchaShear.getCode());
        String code = calculateResult + "";
        SysCaptcha captcha = new SysCaptcha();
        captcha.setUuid(uuid);
        captcha.setCode(code);
        //5分钟后过期
        captcha.setExpireTime(LocalDateTime.now().plusMinutes(5));
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.opsForValue().set(CAPTCHA_REDIS_KEY_PREFIX + uuid, captcha);
        redisTemplate.expire(CAPTCHA_REDIS_KEY_PREFIX + uuid, 6, TimeUnit.MINUTES);
//        this.mapper.insert(captcha);
        return captchaShear.getImage();
    }
    
    /**
     * 验证码效验
     *
     * @param uuid uuid
     * @param code 验证码
     * @return true：成功  false：失败
     */
    @Override
    public boolean validate(String uuid, String code){
        SysCaptcha sysCaptcha = redisTemplate.opsForValue().get(CAPTCHA_REDIS_KEY_PREFIX + uuid);
//        SysCaptcha sysCaptcha = this.mapper.selectOneById(uuid);
        if(sysCaptcha == null){
            return false;
        }
        redisTemplate.delete(CAPTCHA_REDIS_KEY_PREFIX + uuid);
//        this.mapper.deleteById(uuid);
        return sysCaptcha.getCode().equalsIgnoreCase(code) && sysCaptcha.getExpireTime().isAfter(LocalDateTime.now());
    }
}
